/*
 * pixelpipe.cpp
 *
 *  Created on: 19-Oct-2009
 *      Author: pmui
 */

#include <QtCore>
#include <QHttp>
#include <QDebug>
#include <QFile>
#include "twitpic.h"

TwitPic::TwitPic()
{
	m_manager = new QNetworkAccessManager(this);
	connect(m_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(responseReceived(QNetworkReply*)));
}

void TwitPic::upload(const QString &photo)
{
	qDebug() << "uploading" << photo;

	QUrl url("http://twitpic.com/api/upload");
	QNetworkRequest req(url);
	req.setUrl(url);
	
	QString boundary="---------------------------boundary123";
	
	req.setRawHeader("Content-Type","multipart/form-data; boundary=---------------------------boundary123");
	
	QByteArray *data = new QByteArray();
	
	// username
	data->append(QString("--" + boundary + "\r\n").toAscii());
	data->append(QString("Content-Disposition: form-data; name=\"username\"\r\n\r\n").toAscii());
	data->append("hybridwidget");
	data->append("\r\n");
	
	// password
	data->append(QString("--" + boundary + "\r\n").toAscii());
	data->append(QString("Content-Disposition: form-data; name=\"password\"\r\n\r\n").toAscii());
	data->append("hybridwidget1");
	data->append("\r\n");
	
	// photo
	QFile file(photo);
	file.open(QIODevice::ReadOnly);
	data->append(QString("--" + boundary + "\r\n").toAscii());
	
	QFileInfo fileInfo(photo);
	
	data->append(QString("Content-Disposition: form-data; name=\"media\"; filename=\""+fileInfo.fileName()+"\"\r\n").toAscii());
	data->append(QString("Content-Type: application/octet-stream\r\n").toAscii());
	
	data->append("\r\n");
	data->append(file.readAll());
	data->append("\r\n");
	file.close();

	data->append(QString("\r\n--" + boundary + "--\r\n").toAscii());
		
	QFile dataout("c:\\data.out");
	dataout.open(QIODevice::ReadWrite);
	dataout.write(*data);
	dataout.close();
	
	QNetworkReply* reply = m_manager->post(req, *data);
	
	QFile dataout2("c:\\error.out");
	dataout2.open(QIODevice::ReadWrite);
	dataout2.write(reply->errorString().toAscii());
	dataout2.write(reply->readAll());
	dataout2.close();
}

void TwitPic::responseReceived(QNetworkReply *response)
{
	qDebug() << "http response" << response->errorString();
	
	QFile dataout("c:\\data.in");
	dataout.open(QIODevice::ReadWrite);
	dataout.write(response->errorString().toAscii());
	dataout.write(response->readAll());
	dataout.close();
	
	emit uploadReady();
}

